<?php

namespace app\admin\controller\channel;

use app\common\controller\Backend;
vendor('phpqrcode.phpqrcode');

/**
 * 推广海报
 *
 * @icon fa fa-circle-o
 */
class Poster extends Backend
{
    
    /**
     * Poster模型对象
     * @var \app\admin\model\channel\Poster
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\channel\Poster;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','poster_image','url','createtime','status']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    ###################

    /**
     * 复制链接
     *
     * @return void
     * @author AriFe.Liu 
     */
    public function copyurl(){
        $this->success('',null,['url'=>"http://sh.ljf.com"]);
    }

    /**
     * 下载海报
     *
     * @return void
     * @author AriFe.Liu 
     */
    public function downloadPoster(){
        $ids = $this->request->param('ids');
        if(!$ids) $this->alertError("如果确定已经选中了指定海报,请将此错误报至工作人员!");
        $poster = db('ChannelPoster')->where(['id'=>$ids])->find();
        if(!$poster) $this->alertError('啊哦~这张海报可能不小心走丢了呢');
        $channel_code = db('Channel')->where(['admin_id'=>$this->auth->id])->value('code');
        $filename = $this->getChannelPoster($channel_code,$ids);
        $this->outputFile($filename,$poster['title'].'.png');
    }

    /**
     * 下载二维码
     *
     * @return void
     * @author AriFe.Liu 
     */
    public function downloadQrcode(){
        $ids = $this->request->param('ids');
        if(!$ids) $this->alertError("如果确定已经选中了指定二维码,请将此错误报至工作人员!");
        $channel = db('Channel')->where(['admin_id'=>$this->auth->id])->find();
        $channel_code = $channel['code'];
        if(!$channel_code) $this->alertError("您当前尚无邀请码,无法下载!");
        $filename = $this->getChannelQrcode($channel_code,$ids);
        $this->outputFile($filename,$channel['truename'].'.png');
    }

    
    /**
     * 合成图片
     *
     * @param string $dst_path 底图
     * @param string $src_path 覆盖图
     * @param string $newpath 保存路径
     * @param integer $x 覆盖图位于底图的相对X坐标
     * @param integer $y 覆盖图位于底图的相对Y坐标
     * @return void
     * @author AriFe.Liu 
     */
    private function mergeImg($dst_path,$src_path,$newpath,$x=0,$y=0){
        # 合成图片
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($src_path));
        list($src_w,$src_h) = getimagesize($src_path);
        imagecopymerge($dst,$src,$x,$y,0,0,$src_w,$src_h,100);
        # 写入文字到图片
        // $font_size = 22; # 字体大小
        // $fontfile = ROOT_PATH."public/fonts/pingfang.ttf";
        // // // echo $fontfile;die;
        // $color = imagecolorallocate($dst,255,255,255);
        // imagettftext($dst,$font_size,0,$poster['qrcode_x'],$poster['qrcode_y']-40,$color,$fontfile,$text);
        imagepng($dst,$newpath);
        // imagedestroy($dst);
        if(!file_exists($newpath)){
            // exception('MERGE_IMG HAS ERROR OPEN.');
            return false;
        }
        return $newpath;
    }

    /**
     * 浏览器下载
     *
     * @param string $filename
     * @param string $newname
     * @return void
     * @author AriFe.Liu 
     */
    private function outputFile($filename,$newname=""){
        if(empty($newname)){
            $newname = basename($filename);
        }
        //设置头信息
        header('Content-Disposition:attachment;filename='.$newname );
        header('Content-Length:' . filesize($filename));
        //读取文件并写入到输出缓冲
        readfile($filename);
    }

    /**
     * Browser 弹出错误提示并返回上一页
     *
     * @param [type] $msg
     * @return void
     * @author AriFe.Liu 
     */
    private function alertError($msg){
        echo "<script>alert('{$msg}');history.back();</script>";
        die;
    }

    /**
     * 获取海报
     *
     * @param string $channel_code 渠道邀请码
     * @param int $poster_id 海报ID
     * @return void
     * @author AriFe.Liu 
     */
    private function getChannelPoster($channel_code,$poster_id){
        $channel_poster_path = ROOT_PATH.'public/channel/poster/'.$channel_code.'_'.$poster_id.'.png';
        if(file_exists($channel_poster_path)){
            return $channel_poster_path;
        }
        # 不存在, 则要开始创建了.
        ##########
        # 源海报路径
        $poster = db('ChannelPoster')->where(['id'=>$poster_id])->find();
        $poster_path = ROOT_PATH.'public'.$poster['poster_image'];
        $qrcode_path = $this->getChannelQrcode($channel_code,$poster_id);
        if(!file_exists($poster_path)){
            $this->error('海报源文件丢失');
        }
        if(!file_exists($qrcode_path)){
            $this->error('用户二维码未生成');
        }
        $res = $this->mergeImg($poster_path,$qrcode_path,$channel_poster_path,$poster['xpos'],$poster['ypos']);
        if($res === false){
            $this->error('MERGE_IMG HAS ERROR OPEN.');
        }
        return $channel_poster_path;
    }

    /**
     * 获取二维码
     *
     * @param string $channel_code
     * @param int $poster_id
     * @return void
     * @author AriFe.Liu 
     */
    private function getChannelQrcode($channel_code,$poster_id){
        $qrcode_path = ROOT_PATH.'public/channel/qrcode/'.$channel_code.'.png';
        if(file_exists($qrcode_path)){
            return $qrcode_path;
        }
        $data = db('ChannelPoster')->where(['id'=>$poster_id])->value('url');
        $data .= $channel_code;
        # 不存在, 需要合成qrcode到指定路径
        $level = 'L';// 纠错级别：L、M、Q、H
        $margin = 1;//边距
        $saveandprint = false;// true直接输出屏幕  false 保存到文件中
        $back_color = 0xFFFFFF;//白色底色
        $fore_color = 0x000000;//        
        //生成png图片
        $size = 5;
        \QRcode::png($data, $qrcode_path, $level, $size, $margin, $saveandprint, $back_color, $fore_color);
        
        return $qrcode_path;
    }

}
